#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <iostream>


int main(){
    /*1.创建侦听套接字*/
    int listen_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(listen_sockfd < 0){
        perror("socket");
        return 0;
    }
    /*2.绑定地址信息（IP，PORT）*/
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(38989); 
    addr.sin_addr.s_addr = inet_addr("0.0.0.0"); /* 0.0.0.0: 表示当前机器当中的任意一块网卡地址 */
    int ret = bind(listen_sockfd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret < 0){
        perror("bind");
        return 0;
    }
    /*3.监听*/
    ret = listen(listen_sockfd, 1);
    if(ret < 0){
        perror("listen");
        return 0;
    }
    while(1){
        /*4.获取新连接*/
        int new_sockfd = accept(listen_sockfd, NULL, NULL);
        if(new_sockfd < 0){
            perror("accept");
            return 0;
        }

        /*5.收发数据*/
        char buf[1024] = {0};
        ssize_t recv_size = recv(new_sockfd, buf, sizeof(buf) - 1, 0);
        if(recv_size < 0){
            perror("recv");
            return 0;
        }else if(recv_size == 0){
            //对端将连接关闭掉了
            close(new_sockfd);
            return 0;
        }else{
            printf("client say: %s\n", buf);
        }

        memset(buf, '\0', 1024);
        printf("please enter: ");
        fflush(stdout);

        std::cin >> buf;
        //strcpy(buf, "i am server");
        send(new_sockfd, buf, strlen(buf), 0);
    }
    /*6.关闭套接字*/
    close(listen_sockfd);
    return 0;
}
